package com.hunan.api.catv.service.biz.smartfamily;

import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.entity.enums.SmartFamilyInfoTypeEnum;
import com.hunan.api.catv.entity.enums.SmartFamilyMsgTemplateEnum;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.impl.member.MemberService;
import com.hunan.api.catv.service.impl.smartfamily.SmartService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jiang zhuan
 * @version 1.0
 * @description 描述
 * @date 2021/11/15 0015
 * @package com.hunan.api.catv.service.biz.smart_family
 * @company 湖南有线
 */
@Service
public class SmartFamilyBiz extends ResultService {
    private static final String SMART_FAMILY_ACCESS_TOKEN = "smart::AccessToken";
    private static final String SMART_FAMILY_UN_LOGIN = "loginFail";
    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    SmartService smartService;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberService memberService;

    public String login(Integer memberId) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.smart_family_service_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            String domain = conf.get("domain").getAsString();
            String appKey = conf.get("appKey").getAsString();
            String appSecret = conf.get("appSecret").getAsString();
            MultiValueMap<String, Object> paraMap = new LinkedMultiValueMap<>();
            paraMap.add("appKey", appKey);
            paraMap.add("appSecret", appSecret);
            paraMap.add("memberId", memberId);
            MemberVo memberVo = memberService.getById(memberId);
            if (memberVo != null) {
                paraMap.add("nickName", memberVo.getNickName());
                paraMap.add("avatarUrl", memberVo.getAvatarUrl());
            }
            JsonObject info = smartService.getToken(domain, paraMap);
            if (!ObjectUtils.isEmpty(info)) {
                log.info("蜗牛智家token调用结果:{}", info);
                String code = info.get("code").getAsString();
                if ("200".equals(code)) {
                    JsonObject data = info.get("data").getAsJsonObject();
                    redisUtils.hset(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId), data.get("accessToken").getAsString(), data.get("expire").getAsLong());
                    return data.get("accessToken").getAsString();
                }

            }
        }
        return null;
    }

    public Object simpleInfo(Integer memberId) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.smart_family_service_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            Object token = redisUtils.hget(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId));
            if (ObjectUtils.isEmpty(token)) {
                login(memberId);
                token = redisUtils.hget(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId));
            }
            String domain = conf.get("domain").getAsString();
            MultiValueMap<String, Object> paraMap = new LinkedMultiValueMap<>();
            JsonObject info = smartService.simpleInfo(domain, paraMap, token);
            if (!ObjectUtils.isEmpty(info)) {
                log.info("蜗牛智家消息读取状态结果:{}", info);
                String code = info.get("code").getAsString();
                if ("200".equals(code)) {
                    JsonElement data = info.get("data");
                    return wrap(data);
                }
                if ("10002".equals(code)) {
                    redisUtils.hdel(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId));
                    token = login(memberId);
                    info = smartService.simpleInfo(domain, paraMap, token);
                    if (!ObjectUtils.isEmpty(info)) {
                        log.info("蜗牛智家消息读取状态结果:{}", info);
                        code = info.get("code").getAsString();
                        if ("200".equals(code)) {
                            JsonElement data = info.get("data");
                            return wrap(data);
                        }
                    }

                }
            }
        }
        return null;
    }

    private JsonObject wrap(JsonElement data) {
        if (data == null) {
            return new JsonObject();
        }
        JsonObject origin = data.getAsJsonObject();
        JsonObject shareHome = origin.getAsJsonObject("shareHome");
        concatMsg(shareHome, "shareHome", new String[]{"ownerNickName", "homeName", "nickName"});
        JsonObject shareDevice = origin.getAsJsonObject("shareDevice");
        concatMsg(shareDevice, "shareDevice", new String[]{"ownerNickName", "deviceName", "nickName"});
        JsonObject alarm = origin.getAsJsonObject("alarm");
        concatMsg(alarm, "alarm", new String[]{"alarmTime", "deviceName", "describe"});
        return origin;
    }

    private void concatMsg(JsonObject element, String name, String[] paramNames) {
        JsonElement she = element.get("data");
        if (she instanceof JsonNull) {
            element.addProperty("msg", "");
        } else {
            JsonObject sho = she.getAsJsonObject();
            JsonObject body = sho.getAsJsonObject("body");
            int state = body.get("state") == null ? 0 : body.get("state").getAsInt();
            Map<String, String> params = new HashMap<>();
            params.put("msgTime", sho.get("msgTime") == null ? "" : sho.get("msgTime").getAsString());
            for (String paramName : paramNames) {
                params.put(paramName, body.get(paramName) == null ? "" : body.get(paramName).getAsString());
            }
            element.addProperty("msg", SmartFamilyMsgTemplateEnum.getMsg(name, state, params));
            element.remove("data");
        }
    }

    public Object msgList(Integer pageNum, Integer pageSize, Integer type, Integer memberId) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.smart_family_service_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            Object token = redisUtils.hget(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId));
            if (ObjectUtils.isEmpty(token)) {
                login(memberId);
                token = redisUtils.hget(SMART_FAMILY_ACCESS_TOKEN, String.valueOf(memberId));
            }
            String domain = conf.get("domain").getAsString();
            MultiValueMap<String, Object> paraMap = new LinkedMultiValueMap<>();
            paraMap.add("msgType", SmartFamilyInfoTypeEnum.getName(type));
            paraMap.add("pageNo", pageNum);
            paraMap.add("pageSize", pageSize);
            JsonObject info = smartService.msgList(domain, paraMap, token);
            if (!ObjectUtils.isEmpty(info)) {
                log.info("蜗牛智家消息详细列表结果:{}", info);
                String code = info.get("code").getAsString();
                if ("200".equals(code)) {
                    JsonObject data = info.get("data").getAsJsonObject();
                    return data;
                }

            }
        }
        return null;
    }
}
